package com.lambo.maven.core.utils.superHttp.core;

import java.net.URL;

public class ProxyHostsMatcher {

	private static String[] nonProxyHosts = {
		"localhost", "127.*", "10.*"
	};

	public static void setNonProxyHosts(String[] strs) {
		nonProxyHosts = strs;
	}
	
	private static final String[] FUZZY_PATTERNS = {
		"[\\w-]+\\.\\*", 									//10.* | supply-test.*
		"[\\w-]+\\.[\\w-]+\\.\\*",							//10.13.* | supply-test.ztwltech.*
		"[\\w-]+\\.[\\w-]+\\.[\\w-]+\\.\\*"					//10.13.1.* | supply-test.ztwltech.pay.*
	}; 
	
	// static {
	// 	String config = CommonProp.get("custom.config.non-proxy-hosts");
	// 	nonProxyHosts = config.split("\\|");
	// }
	
	/**
	 * 是否代理
	 * @param url
	 * @return
	 */
	private static boolean useProxy(URL url) {
		String host = url.getHost();
		return !isMatchNonProxyHosts(host);
	}

	public static boolean useProxy(String url) {
		try{
			URL _url = new URL(url);
			return useProxy(_url);
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 请求的地址是否匹配非代理地址
	 * @param host
	 * @return
	 */
	private static boolean isMatchNonProxyHosts(String host) {
		boolean isNonProxy = false;
		if(nonProxyHosts == null) {
			return false;
		}
		for (String nonProxyHost : nonProxyHosts) {
			if (isFuzzyPattern(nonProxyHost)) {
				// 如果是模糊匹配，以剔除*为开头的
				isNonProxy = host.startsWith(StringUtils.substringBeforeLast(nonProxyHost, "*"));
			} else {
				// 是否匹配具体匹配
				isNonProxy = host.equalsIgnoreCase(nonProxyHost);
			}
			if (isNonProxy) {
				return isNonProxy;
			}
		}
		return false;
	}
	
	
	/**
	 * 是否模糊匹配
	 * @param pattern
	 * @return
	 */
	private static boolean isFuzzyPattern(String pattern) {
		for (String fuzzy : FUZZY_PATTERNS) {
			if (pattern.matches(fuzzy)) {
				return true;
			}
		}
		return false;
	}
	
}
